<?php
/**
 * Created by phpstorem.
 * User: yangakw@qq.com
 * Sign: 猥琐发育，别浪
 * Date: 2017/10/5 0005
 * Time: 下午 9:50
 */

namespace src;


use conf\Config;

class Parse
{
    /** @var  DownLoad */
    public $download;

    public function __construct($download)
    {
        $this->download = $download;
    }

    public function analysls(Item $item)
    {

        if (!isset($item->value) || empty($item->value)) {
            Queue::error($item, "url get html is empty");
        }
        $handle = $item->handle;
        if (method_exists($this, $handle)) {
            $html = $item->value;
            $dom = str_get_html($html);
            if (!($dom instanceof \simple_html_dom)) {
                Queue::error($item, "html can not parse sml_domimpleht");
            }
            ##没有问题  开始分析页面
            echo "\n\n........doing \\src\\Parse->{$handle}() \n\n";
            call_user_func([$this, $handle], $dom, $item);
            Queue::done($item);
        } else {
            Queue::error($item, "not define function $handle in Parse,so can not analysls this page");
        }
    }

    /**
     * @param \simple_html_dom $dom
     * @param Item $item
     * @return bool
     */
    public function web(\simple_html_dom $dom, Item $item)
    {
        $list_a = $dom->find("a");
        foreach ($list_a as $a) {
            if (isset($a->href)) {
                $url = $a->href;
                $_item = $this->download->get($url, "web");
                if (strpos($url, "question") > 0) {
                   if($_item){
                       $html = $_item->value;
                       $this->question($html);
                   }
                }
                Queue::doing($_item);
            }
        }
        return true;
    }

    public function question($html)
    {
        $ask_tit=false;
        $ask_hid=false;
        $ask = new Ask();
        $dom = str_get_html($html);
//        $title = $dom->find("title",0);
//        exit($title->innertext);
        if(!$dom){
            return;
        }
        $ask_tit_ = $dom->find(".ask_cont .ask_tit",0);
        if(isset($ask_tit_->innertext)){
            $ask_tit = $ask_tit_->innertext;
        }
        $ask_hid_ = $dom->find(".ask_cont .ask_hid",0);
        if(isset($ask_hid_->innertext)){
            $ask_hid = $ask_hid_->innertext;
        }
        $sele_txt = $dom->find(".selected .sele_all .sele_txt");
        $sele_question=[];
        foreach($sele_txt as $q){
            isset($q->innertext)?
                $sele_question[]=strip_tags($q->innertext) : null;
        }
        if($ask_tit && $ask_tit ){
            $ask->ask_tit=strip_tags($ask_tit);
            $ask->ask_hid=strip_tags($ask_hid);
            $ask->sele_question=$sele_question;
            $ask->commit();
            $ask->save();
        }
    }


    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        echo "\n\n...doing {$name}....\n\n";
    }

}